﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Attributes;
using ZhonTai.Industry.Contracts.Core.Enums;
using ZhonTai.Industry.Contracts.Model.Entity;
using ZhonTai.Industry.Core.Core.Common;
using ZhonTai.Industry.Domain.GenericBinding;

namespace ZhonTai.Industry.Core.Core.CraftGather.BatchSave
{
    /// <summary>
    /// 批次处理操作
    /// </summary>
    [InjectScoped]
    public class BatchSaveHandle : WorkExecuteBase
    {
        private readonly IGenericBindingRepository _genericBindingRepository;

        public BatchSaveHandle(IGenericBindingRepository genericBindingRepository)
        {
            _genericBindingRepository = genericBindingRepository;
        }

        public override async Task ExecuteAsync(PushShip content)
        {
            try
            {
                //获得mes方批次回复地址
                var mesDB = content.Example._mesDB.DataFields.Find(x => x.GroupName == content.GroupName);
                //批次地址
                List<DBField> batchParam = content.Example._plcDB.DataFields.FindAll(f => f.GroupName == content.GroupName);
                foreach (var param in batchParam)
                {
                    //批次条码
                    string batchCode = content.Example.TryGetValue<string>(param.Another);
                    if (batchCode == "")
                    {
                        var result = await content.Example.WriteAsync(mesDB.Offset, (short)SaveResultEnum.EmptyMasterCode);
                        if (result.IsSuccess)
                        {
                            logger.Warn($"保存请求：工站【{content.OPCode}】条码不存在，回复【{SaveResultEnum.EmptyMasterCode}】写入成功！");
                        }
                        return;
                    }
                    //判断是否是清洗篮扫描
                    if (batchCode.Substring(0, 2) == "QX")
                    {
                        var gendericEntity = await _genericBindingRepository.Select.Where(x => x.CodeA == batchCode && x.BindingType == "BatchBind").ToOneAsync();
                        if (gendericEntity == null)
                        {
                            var Result = await content.Example.WriteAsync(mesDB.Offset, (short)SaveResultEnum.Fail);
                            if (Result.IsSuccess)
                            {
                                logger.Error($"批次保存请求：工站【{content.OPCode}】清洗篮条码系统不存在，回复【{SaveResultEnum.EmptyMasterCode}】写入成功！");
                            }
                            return;
                        }
                        //解析批次数量进行填充
                        var batchStr = gendericEntity.CodeB.Split('@');
                        //启用批次状态并设置清洗篮绑定工位
                        gendericEntity.StationId = content.StationId;
                        gendericEntity.Label = content.GroupName switch
                        {
                            "SB1" => "1",
                            "SB2" => "2",
                            "SB3" => "3",
                            "SB4" => "4",
                            "SB5" => "5",
                            "SB6" => "6",
                            "SB7" => "7",
                            _ => ""
                        };
                        gendericEntity.Count = Convert.ToInt32(batchStr[1]);
                        gendericEntity.Status = StatusEnum.Open;
                        await _genericBindingRepository.UpdateAsync(gendericEntity);
                    }
                    else//针对不是清洗篮情况
                    {
                        var batchStr = batchCode.Split('@');
                        GenericBindingEntity entity = new GenericBindingEntity()
                        {
                            StationId = content.StationId,
                            BindingType = "BatchBind",
                            CodeA = batchCode,
                            CodeB = batchCode,
                            Count = Convert.ToInt32(batchStr[1]),
                            Status = StatusEnum.Open
                        };
                        await _genericBindingRepository.InsertAsync(entity);
                    }
                }
                var otherResult = await content.Example.WriteAsync(mesDB.Offset, (short)SaveResultEnum.Success);
                //复位物料报警
                var batchReset = await content.Example.WriteAsync(0, (short)1);
                if (otherResult.IsSuccess && batchReset.IsSuccess)
                {
                    logger.Info($"批次保存请求：工站【{content.OPCode}】批次绑定配置成功，回复【{SaveResultEnum.EmptyMasterCode}】写入成功！");
                }
            }
            catch (Exception ex)
            {
                var writeResult = await content.Example.WriteAsync(2000, (short)SaveResultEnum.Abnormal);
                if (writeResult.IsSuccess)
                {
                    logger.Error($"工站【{content.OPCode}】批次保存错误，原因:{ex.Message},回复写入成功");
                }
            }
        }
    }
}